package com.xbdun.web.validatebmp.facade.email;

import java.util.Date;

import javax.mail.internet.MimeMessage;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.xbdun.common.api.XbdUnStringResult;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.facade.validatebmp.exceptions.ValidateBizException;
import com.xbdun.facade.validatebmp.menus.EmailTempletEnum;
import com.xbdun.facade.validatebmp.request.SimpleMailMessageRequest;
import com.xbdun.facade.validatebmp.request.TemplateMailRequest;
import com.xbdun.facade.validatebmp.service.email.EmailFacade;

import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

//邮件操作
@Component
@Slf4j
public class EmailFacadeImpl implements EmailFacade{
	@Autowired
	private JavaMailSender mailSender;
	@Autowired  
    private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@Value("${spring.mail.username}")
	String userName;//邮件发送者
	/**
	* @Title: sendSimpleMailMessage
	* @Description 发送简单邮件
	* @param reqeust 简单邮件请求对象
	* @return XbdUnStringResult    返回类型
	 */
	public XbdUnStringResult sendSimpleMailMessage(SimpleMailMessageRequest reqeust){
		XbdUnStringResult result = new XbdUnStringResult();
		result.setBizException(ValidateBizException.EIMAL_SEND_FAIL);
		try{
			log.info("start 发送邮件信息，入参:{}",reqeust);
			SimpleMailMessage message = new SimpleMailMessage();
			//邮件内容
			BeanUtils.copyProperties(message, reqeust);
			
			message.setFrom(userName);//发送者.
			if(null == message.getTo()||message.getTo().length==0){
				message.setTo(userName);//发给自己
			}
			message.setSentDate(new Date());//发送邮件日期
			if(null !=reqeust.getTos()&&reqeust.getTos().length>0){
				message.setTo(reqeust.getTos());
			}
			
			mailSender.send(message);//发送邮件
			result.setBizException(BizException.SUCCESS);//发送成功
		}catch(Exception e){
			log.error("发送邮件信息，异常:{}",reqeust);
		}finally{
			log.info("end 发送邮件信息，结果:{}",result);
		}
		return result;
	}
	
	/**
	* @Title: sendTemplateMail
	* @Description: 模板发送邮件
	* @return    设定文件
	* @return XbdUnStringResult    返回类型
	 */
	public XbdUnStringResult sendTemplateMail(TemplateMailRequest reqeust){
		XbdUnStringResult result = new XbdUnStringResult();
		result.setBizException(ValidateBizException.EIMAL_SEND_FAIL);
		try{
			log.info("start 发送邮件信息，入参:{}",reqeust);

			chekedSendTemplateMail(reqeust);
	        MimeMessage mimeMessage = mailSender.createMimeMessage();
	        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
	        //邮件内容
			BeanUtils.copyProperties(helper, reqeust);
			if(null !=reqeust.getTos()&&reqeust.getTos().length>0){
				helper.setTo(reqeust.getTos());
			}
			helper.setFrom(userName);//发送者.
			helper.setSentDate(new Date());//发送邮件日期
			reqeust.getTempParams().put("toEmail",StringUtils.isBlank(reqeust.getTo())?reqeust.getTos()[0]+" ...":reqeust.getTo());
	        Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email/"+reqeust.getTempletName().toLowerCase());//加载资源文件  
	        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, reqeust.getTempParams());
	        helper.setText(html, true);

	        mailSender.send(mimeMessage);
	        
			result.setBizException(BizException.SUCCESS);//发送成功
		}catch(Exception e){
			log.error("发送邮件信息，异常:{}",reqeust);
		}finally{
			log.info("end 发送邮件信息，结果:{}",result);
		}
		return result;
	}

	//参数校验
	private void chekedSendTemplateMail(TemplateMailRequest reqeust) {
		StringBuilder sb = new StringBuilder();
		
		if(null==EmailTempletEnum.getEnum(reqeust.getTempletName())&&(null==reqeust.getTempletCode()||reqeust.getTempletCode().longValue()<=0)){
			sb.append("发送邮件的模板名称与模板编号不能同时为空;");
		}
		if(null==reqeust.getTempParams()||reqeust.getTempParams().isEmpty()){
			sb.append("模板对应Map不能为空");
		}
		if(sb.length()>0){
			throw ValidateBizException.EIMAL_SEND_FAIL.newInstance(sb.toString());
		}
	}
}